package com.hsd.service.impl;

import com.hsd.mapper.IAccountDao;
import com.hsd.entity.Account;
import com.hsd.service.IAccountService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class IAccountServiceImpl implements IAccountService {
    @Resource
    private IAccountDao accountDao;

    @Override
    public boolean save(String acc, Double money) {
        return accountDao.updateMoney(acc, money) > 0;
    }

    @Override
    public boolean take(String acc, Double money) {
        Account account = findByAcc(acc);
        Double balance = account.getMoney();
        if (balance < money) {
            throw new RuntimeException("余额不足");
        } else {
            return accountDao.updateMoney(acc, -money) > 0;
        }
    }

    @Override
    public boolean transfer(String from, String to, Double money) {
        boolean take = take(from, money);
        boolean save = save(to, money);
        if (!take && save) {
            throw new RuntimeException("存取失败");
        } else {
            return take && save;
        }
    }

    @Override
    public Account findByAcc(String acc) {
        return accountDao.selectByAcc(acc);
    }

    @Override
    public List<Account> findAll() {
        return accountDao.selectAll();
    }
}
